<template>
  <div class="settings-container">
    <div class="settings-header">
      <div class="header-left">
        <el-button @click="$router.push('/')" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回首页
        </el-button>
        <h1 class="settings-title">个人设置</h1>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="$router.push('/profile')">查看个人主页</el-button>
      </div>
    </div>

    <div class="settings-content">
      <div class="settings-sidebar">
        <el-menu
          :default-active="activeMenuItem"
          class="settings-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="profile">
            <el-icon><UserFilled /></el-icon>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="account">
            <el-icon><Lock /></el-icon>
            <span>账号安全</span>
          </el-menu-item>
          <el-menu-item index="notification">
            <el-icon><Bell /></el-icon>
            <span>通知设置</span>
          </el-menu-item>
          <el-menu-item index="privacy">
            <el-icon><View /></el-icon>
            <span>隐私设置</span>
          </el-menu-item>
        </el-menu>
        
        <div class="logout-section">
          <el-button type="danger" @click="handleLogout" class="logout-button">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </div>

      <div class="settings-main">
        <!-- 个人信息设置 -->
        <div v-if="activeMenuItem === 'profile'" class="settings-panel">
          <h2 class="panel-title">个人信息</h2>
          <el-form 
            :model="profileForm" 
            :rules="profileRules" 
            ref="profileFormRef" 
            label-width="100px"
            class="settings-form"
          >
            <div class="avatar-container">
              <el-avatar :size="100" :src="profileForm.avatar || defaultAvatar"></el-avatar>
              <div class="avatar-info">
                <h3>个人头像</h3>
                <p class="avatar-tip">上传一个清晰的头像有助于其他用户认识你</p>
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload/avatar"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :headers="uploadHeaders"
                >
                  <el-button type="primary">更换头像</el-button>
                </el-upload>
              </div>
            </div>

            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" placeholder="请输入昵称"></el-input>
            </el-form-item>

            <el-form-item label="性别">
              <el-radio-group v-model="profileForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                <el-radio :label="0">保密</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="个人简介">
              <el-input
                type="textarea"
                v-model="profileForm.bio"
                placeholder="介绍一下自己吧"
                :rows="4"
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item label="职业">
              <el-input v-model="profileForm.profession" placeholder="请输入职业"></el-input>
            </el-form-item>

            <el-form-item label="所在地区">
              <el-cascader
                v-model="profileForm.location"
                :options="locationOptions"
                placeholder="请选择所在地区"
              ></el-cascader>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveProfile" :loading="saving">保存修改</el-button>
              <el-button @click="resetForm('profileFormRef')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 账号安全设置 -->
        <div v-if="activeMenuItem === 'account'" class="settings-panel">
          <h2 class="panel-title">账号安全</h2>
          
          <div class="security-section">
            <h3 class="section-title">修改密码</h3>
            <el-form 
              :model="passwordForm" 
              :rules="passwordRules" 
              ref="passwordFormRef" 
              label-width="100px"
              class="settings-form"
            >
              <el-form-item label="当前密码" prop="oldPassword">
                <el-input 
                  v-model="passwordForm.oldPassword" 
                  type="password" 
                  placeholder="请输入当前密码"
                  show-password
                ></el-input>
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  v-model="passwordForm.newPassword" 
                  type="password" 
                  placeholder="请输入新密码"
                  show-password
                ></el-input>
                <div class="form-tip">密码至少包含6个字符</div>
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input 
                  v-model="passwordForm.confirmPassword" 
                  type="password" 
                  placeholder="请再次输入新密码"
                  show-password
                ></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="updatePasswordHandler" :loading="saving">修改密码</el-button>
                <el-button @click="resetForm('passwordFormRef')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="security-section">
            <h3 class="section-title">绑定邮箱</h3>
            <div class="bind-status">
              <div class="status-info">
                <span class="label">当前绑定邮箱：</span>
                <span class="value">{{ userEmail || '未绑定' }}</span>
              </div>
              <el-button type="primary" @click="showEmailBindDialog">
                {{ userEmail ? '修改绑定' : '绑定邮箱' }}
              </el-button>
            </div>
            <div class="form-tip">绑定邮箱可以提高账号安全性，也可以用于接收通知</div>
          </div>
        </div>

        <!-- 通知设置 -->
        <div v-if="activeMenuItem === 'notification'" class="settings-panel">
          <h2 class="panel-title">通知设置</h2>
          <el-form :model="notificationForm" label-width="160px" class="settings-form">
            <div class="security-section">
              <h3 class="section-title">站内消息</h3>

              <el-form-item label="问题回答通知">
                <el-switch v-model="notificationForm.notifyOnAnswer"></el-switch>
                <span class="switch-label">当您的问题有新回答时接收通知</span>
              </el-form-item>

              <el-form-item label="回答评论通知">
                <el-switch v-model="notificationForm.notifyOnComment"></el-switch>
                <span class="switch-label">当您的回答有新评论时接收通知</span>
              </el-form-item>

              <el-form-item label="回答被采纳通知">
                <el-switch v-model="notificationForm.notifyOnAccept"></el-switch>
                <span class="switch-label">当您的回答被采纳时接收通知</span>
              </el-form-item>

              <el-form-item label="点赞通知">
                <el-switch v-model="notificationForm.notifyOnLike"></el-switch>
                <span class="switch-label">当您的内容被点赞时接收通知</span>
              </el-form-item>
            </div>

            <div class="security-section">
              <h3 class="section-title">界面设置</h3>

              <el-form-item label="深色模式">
                <el-switch v-model="interfaceForm.darkMode"></el-switch>
                <span class="switch-label">启用深色模式</span>
              </el-form-item>

              <el-form-item label="界面语言">
                <el-select v-model="interfaceForm.language" placeholder="选择语言">
                  <el-option label="简体中文" value="zh_CN"></el-option>
                  <el-option label="English" value="en_US"></el-option>
                </el-select>
              </el-form-item>
            </div>

            <el-form-item>
              <el-button type="primary" @click="saveNotificationSettings" :loading="saving">保存设置</el-button>
              <el-button @click="resetNotificationSettings">恢复默认</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 隐私设置 -->
        <div v-if="activeMenuItem === 'privacy'" class="settings-panel">
          <h2 class="panel-title">隐私设置</h2>
          <div class="security-section">
            <el-form :model="privacyForm" label-width="160px" class="settings-form">
              <el-form-item label="在线状态">
                <el-switch v-model="privacyForm.showOnlineStatus"></el-switch>
                <span class="switch-label">允许他人查看我的在线状态</span>
              </el-form-item>

              <el-form-item label="私信">
                <el-switch v-model="privacyForm.allowMessages"></el-switch>
                <span class="switch-label">允许他人给我发送私信</span>
              </el-form-item>

              <el-form-item label="个人主页可见性">
                <el-radio-group v-model="privacyForm.profileVisibility">
                  <el-radio label="public">所有人可见</el-radio>
                  <el-radio label="registered">仅注册用户可见</el-radio>
                  <el-radio label="followers">仅关注者可见</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="我的问题可见性">
                <el-radio-group v-model="privacyForm.questionsVisibility">
                  <el-radio label="public">所有人可见</el-radio>
                  <el-radio label="registered">仅注册用户可见</el-radio>
                  <el-radio label="private">仅自己可见</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="显示我的关注">
                <el-switch v-model="privacyForm.showFollowing"></el-switch>
                <span class="switch-label">允许他人查看我关注的用户</span>
              </el-form-item>

              <el-form-item label="显示我的粉丝">
                <el-switch v-model="privacyForm.showFollowers"></el-switch>
                <span class="switch-label">允许他人查看关注我的用户</span>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="savePrivacySettings" :loading="saving">保存设置</el-button>
                <el-button @click="resetPrivacySettings">恢复默认</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 绑定邮箱弹窗 -->
    <el-dialog
      v-model="emailBindDialogVisible"
      title="绑定邮箱"
      width="400px"
    >
      <el-form :model="emailBindForm" :rules="emailRules" ref="emailFormRef" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="emailBindForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-row">
            <el-input v-model="emailBindForm.captcha" placeholder="请输入验证码"></el-input>
            <el-button 
              :disabled="captchaDisabled" 
              @click="sendCaptcha"
              type="primary"
            >{{ captchaButtonText }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="emailBindDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="bindEmailHandler" :loading="saving">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '../stores/user';
import { updateUserInfo, getCurrentUserInfo } from '../api/user';
import { getCaptcha } from '../api/auth';
import { UserFilled, Lock, Bell, View, SwitchButton, ArrowLeft } from '@element-plus/icons-vue';
import { 
  updatePassword, 
  bindEmail, 
  getUserSettings,
  updateUserSettings,
  updateNotificationSetting,
  updatePrivacySetting,
  updateInterfaceSettings,
  resetUserSettings,
  uploadAvatar
} from '../api/settings';

const router = useRouter();

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';

// 用户数据
const userStore = useUserStore();
const userEmail = computed(() => userStore.userInfo?.email || '');

// 菜单激活项
const activeMenuItem = ref('profile');

// 表单引用
const profileFormRef = ref(null);
const passwordFormRef = ref(null);
const emailFormRef = ref(null);

// 提交状态
const saving = ref(false);

// 个人资料表单
const profileForm = reactive({
  username: '',
  nickname: '',
  avatar: '',
  gender: 0,
  bio: '',
  profession: '',
  location: []
});

// 保存原始表单数据用于重置
const originalProfileData = reactive({});

// 个人资料校验规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
};

// 地区选项（简化版）
const locationOptions = [
  {
    value: '北京',
    label: '北京',
    children: [
      { value: '朝阳区', label: '朝阳区' },
      { value: '海淀区', label: '海淀区' },
      { value: '东城区', label: '东城区' },
      { value: '西城区', label: '西城区' }
    ]
  },
  {
    value: '上海',
    label: '上海',
    children: [
      { value: '黄浦区', label: '黄浦区' },
      { value: '徐汇区', label: '徐汇区' },
      { value: '长宁区', label: '长宁区' },
      { value: '静安区', label: '静安区' }
    ]
  }
];

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码修改校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 邮箱绑定相关
const emailBindDialogVisible = ref(false);
const emailBindForm = reactive({
  email: '',
  captcha: ''
});
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度不正确', trigger: 'blur' }
  ]
};

// 验证码按钮
const captchaDisabled = ref(false);
const captchaButtonText = ref('获取验证码');
let captchaTimer = null;

// 通知设置表单
const notificationForm = reactive({
  notifyOnAnswer: true,
  notifyOnComment: true,
  notifyOnAccept: true,
  notifyOnLike: true,
  emailNotify: false,
  weeklyEmail: false
});

// 默认通知设置
const defaultNotificationSettings = {
  notifyOnAnswer: true,
  notifyOnComment: true,
  notifyOnAccept: true,
  notifyOnLike: true,
  emailNotify: false,
  weeklyEmail: false
};

// 隐私设置表单
const privacyForm = reactive({
  showOnlineStatus: true,
  allowMessages: true,
  profileVisibility: 'public',
  questionsVisibility: 'public',
  showFollowing: true,
  showFollowers: true
});

// 默认隐私设置
const defaultPrivacySettings = {
  showOnlineStatus: true,
  allowMessages: true,
  profileVisibility: 'public',
  questionsVisibility: 'public',
  showFollowing: true,
  showFollowers: true
};

// 界面设置
const interfaceForm = reactive({
  darkMode: false,
  language: 'zh_CN'
});

// 上传头像所需的headers
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  };
});

// 初始化获取用户数据
const loadUserData = async () => {
  try {
    // 获取用户基本信息
    const res = await getCurrentUserInfo();
    const userData = res.data;
    
    // 填充个人资料表单
    profileForm.username = userData.username || '';
    profileForm.nickname = userData.nickname || '';
    profileForm.avatar = userData.avatar || '';
    profileForm.gender = userData.gender || 0;
    profileForm.bio = userData.bio || '';
    profileForm.profession = userData.profession || '';
    profileForm.location = userData.location ? userData.location.split(',') : [];
    
    // 保存原始数据用于重置
    Object.assign(originalProfileData, {
      username: userData.username || '',
      nickname: userData.nickname || '',
      avatar: userData.avatar || '',
      gender: userData.gender || 0,
      bio: userData.bio || '',
      profession: userData.profession || '',
      location: userData.location ? userData.location.split(',') : []
    });
    
    // 加载用户设置数据
    try {
      const settingsRes = await getUserSettings();
      if (settingsRes.code === 200 && settingsRes.data) {
        const settings = settingsRes.data;
        console.log('获取到用户设置:', settings);
        
        // 更新通知设置
        notificationForm.notifyOnAnswer = settings.notifyOnAnswer === 1;
        notificationForm.notifyOnComment = settings.notifyOnComment === 1;
        notificationForm.notifyOnAccept = settings.notifyOnAccept === 1;
        notificationForm.notifyOnLike = settings.notifyOnLike === 1;
        
        // 更新隐私设置
        privacyForm.showOnlineStatus = settings.showOnlineStatus === 1;
        privacyForm.allowMessages = settings.allowMessages === 1;
        
        // 更新界面设置
        interfaceForm.darkMode = settings.darkMode === 1;
        interfaceForm.language = settings.language || 'zh_CN';
      }
    } catch (error) {
      console.error('获取用户设置失败:', error);
      ElMessage.warning('获取用户设置失败，将使用默认设置');
    }
    
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 菜单选择处理
const handleMenuSelect = (index) => {
  activeMenuItem.value = index;
};

// 重置表单
const resetForm = (formName) => {
  if (formName === 'profileFormRef') {
    Object.assign(profileForm, originalProfileData);
  } else if (formName === 'passwordFormRef') {
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';
  }
  
  if (formName && eval(formName).value) {
    eval(formName).value.resetFields();
  }
};

// 重置通知设置
const resetNotificationSettings = async () => {
  try {
    saving.value = true;
    await resetUserSettings();
    
    // 重新获取设置
    const settingsRes = await getUserSettings();
    if (settingsRes.code === 200 && settingsRes.data) {
      const settings = settingsRes.data;
      
      // 更新通知设置
      notificationForm.notifyOnAnswer = settings.notifyOnAnswer === 1;
      notificationForm.notifyOnComment = settings.notifyOnComment === 1;
      notificationForm.notifyOnAccept = settings.notifyOnAccept === 1;
      notificationForm.notifyOnLike = settings.notifyOnLike === 1;
      
      // 更新界面设置
      interfaceForm.darkMode = settings.darkMode === 1;
      interfaceForm.language = settings.language || 'zh_CN';
    }
    
    ElMessage.success('已恢复默认通知设置');
  } catch (error) {
    console.error('重置设置失败:', error);
    ElMessage.error('重置设置失败');
  } finally {
    saving.value = false;
  }
};

// 重置隐私设置
const resetPrivacySettings = async () => {
  try {
    saving.value = true;
    await resetUserSettings();
    
    // 重新获取设置
    const settingsRes = await getUserSettings();
    if (settingsRes.code === 200 && settingsRes.data) {
      const settings = settingsRes.data;
      
      // 更新隐私设置
      privacyForm.showOnlineStatus = settings.showOnlineStatus === 1;
      privacyForm.allowMessages = settings.allowMessages === 1;
    }
    
    ElMessage.success('已恢复默认隐私设置');
  } catch (error) {
    console.error('重置设置失败:', error);
    ElMessage.error('重置设置失败');
  } finally {
    saving.value = false;
  }
};

// 保存个人资料
const saveProfile = async () => {
  if (!profileFormRef.value) return;
  
  try {
    await profileFormRef.value.validate();
    
    saving.value = true;
    await updateUserInfo({
      username: profileForm.username,
      nickname: profileForm.nickname,
      gender: profileForm.gender,
      bio: profileForm.bio,
      profession: profileForm.profession,
      location: profileForm.location.join(',')
    });
    
    // 更新原始数据
    Object.assign(originalProfileData, {
      username: profileForm.username,
      nickname: profileForm.nickname,
      gender: profileForm.gender,
      bio: profileForm.bio,
      profession: profileForm.profession,
      location: [...profileForm.location]
    });
    
    // 刷新用户信息
    await userStore.fetchUserInfo();
    
    ElMessage.success('个人资料更新成功');
  } catch (error) {
    console.error('更新个人资料失败:', error);
    ElMessage.error('更新个人资料失败');
  } finally {
    saving.value = false;
  }
};

// 头像上传成功处理
const handleAvatarSuccess = (res) => {
  if (res.code === 200) {
    profileForm.avatar = res.data;
    originalProfileData.avatar = res.data;
    ElMessage.success('头像上传成功');
    
    // 更新用户资料中的头像
    updateUserInfo({
      avatar: res.data
    }).then(() => {
      // 刷新用户信息
      userStore.fetchUserInfo();
    }).catch(error => {
      console.error('更新头像失败:', error);
    });
  } else {
    ElMessage.error(res.message || '头像上传失败');
  }
};

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 修改密码
const updatePasswordHandler = async () => {
  if (!passwordFormRef.value) return;
  
  try {
    await passwordFormRef.value.validate();
    
    saving.value = true;
    await updatePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    });
    
    ElMessage.success('密码修改成功，请重新登录');
    
    // 清空表单
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';
    
    // 退出登录，跳转到登录页
    await userStore.logoutAction();
    router.push('/login');
  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error(error.message || '修改密码失败');
  } finally {
    saving.value = false;
  }
};

// 显示绑定邮箱弹窗
const showEmailBindDialog = () => {
  emailBindForm.email = userEmail.value || '';
  emailBindForm.captcha = '';
  emailBindDialogVisible.value = true;
};

// 发送验证码
const sendCaptcha = async () => {
  if (!emailBindForm.email) {
    ElMessage.warning('请先输入邮箱地址');
    return;
  }
  
  try {
    captchaDisabled.value = true;
    await getCaptcha(emailBindForm.email);
    
    // 倒计时
    let countdown = 60;
    captchaButtonText.value = `${countdown}秒后重试`;
    
    captchaTimer = setInterval(() => {
      countdown--;
      captchaButtonText.value = `${countdown}秒后重试`;
      
      if (countdown <= 0) {
        clearInterval(captchaTimer);
        captchaButtonText.value = '获取验证码';
        captchaDisabled.value = false;
      }
    }, 1000);
    
    ElMessage.success('验证码已发送到您的邮箱');
  } catch (error) {
    console.error('发送验证码失败:', error);
    ElMessage.error('发送验证码失败');
    captchaDisabled.value = false;
  }
};

// 绑定邮箱
const bindEmailHandler = async () => {
  if (!emailFormRef.value) return;
  
  try {
    await emailFormRef.value.validate();
    
    saving.value = true;
    await bindEmail({
      email: emailBindForm.email,
      captcha: emailBindForm.captcha
    });
    
    ElMessage.success('邮箱绑定成功');
    emailBindDialogVisible.value = false;
    
    // 刷新用户信息
    await userStore.fetchUserInfo();
  } catch (error) {
    console.error('绑定邮箱失败:', error);
    ElMessage.error(error.message || '绑定邮箱失败');
  } finally {
    saving.value = false;
  }
};

// 保存通知设置
const saveNotificationSettings = async () => {
  try {
    saving.value = true;
    
    // 整合设置数据
    const userSettings = {
      notifyOnAnswer: notificationForm.notifyOnAnswer ? 1 : 0,
      notifyOnComment: notificationForm.notifyOnComment ? 1 : 0,
      notifyOnAccept: notificationForm.notifyOnAccept ? 1 : 0,
      notifyOnLike: notificationForm.notifyOnLike ? 1 : 0,
      language: interfaceForm.language,
      darkMode: interfaceForm.darkMode ? 1 : 0
    };
    
    // 调用更新设置接口
    await updateUserSettings(userSettings);
    
    // 如果需要单独更新各个设置，可以使用下面的代码
    /*
    // 更新问题回答通知
    await updateNotificationSetting('answer', notificationForm.notifyOnAnswer);
    
    // 更新回答评论通知
    await updateNotificationSetting('comment', notificationForm.notifyOnComment);
    
    // 更新回答采纳通知
    await updateNotificationSetting('accept', notificationForm.notifyOnAccept);
    
    // 更新点赞通知
    await updateNotificationSetting('like', notificationForm.notifyOnLike);
    
    // 更新界面设置
    await updateInterfaceSettings(interfaceForm.darkMode, interfaceForm.language);
    */
    
    ElMessage.success('通知设置已保存');
  } catch (error) {
    console.error('保存通知设置失败:', error);
    ElMessage.error('保存通知设置失败');
  } finally {
    saving.value = false;
  }
};

// 保存隐私设置
const savePrivacySettings = async () => {
  try {
    saving.value = true;
    
    // 整合设置数据
    const userSettings = {
      showOnlineStatus: privacyForm.showOnlineStatus ? 1 : 0,
      allowMessages: privacyForm.allowMessages ? 1 : 0
    };
    
    // 调用更新设置接口
    await updateUserSettings(userSettings);
    
    // 如果需要单独更新各个设置，可以使用下面的代码
    /*
    // 更新在线状态设置
    await updatePrivacySetting('online_status', privacyForm.showOnlineStatus);
    
    // 更新私信设置
    await updatePrivacySetting('messages', privacyForm.allowMessages);
    */
    
    ElMessage.success('隐私设置已保存');
  } catch (error) {
    console.error('保存隐私设置失败:', error);
    ElMessage.error('保存隐私设置失败');
  } finally {
    saving.value = false;
  }
};

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await userStore.logoutAction();
    ElMessage.success('已退出登录');
    router.push('/login');
  }).catch(() => {});
};

// 组件挂载时加载数据
onMounted(() => {
  loadUserData();
  
  return () => {
    if (captchaTimer) {
      clearInterval(captchaTimer);
    }
  };
});
</script>

<style scoped>
.settings-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.settings-header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-btn {
  margin-right: 16px;
  font-size: 14px;
}

.settings-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.settings-content {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 600px;
}

.settings-sidebar {
  width: 220px;
  background-color: #f8f8f8;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.settings-menu {
  border-right: none;
  flex: 1;
}

.logout-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.logout-button {
  width: 100%;
}

.settings-main {
  flex: 1;
  padding: 24px 30px;
  overflow-y: auto;
}

.settings-panel {
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.panel-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  color: #409EFF;
}

.settings-form {
  max-width: 600px;
}

.avatar-container {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 8px;
}

.avatar-uploader {
  margin-left: 24px;
}

.security-section {
  margin-bottom: 36px;
  background: #fcfcfc;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 20px;
  color: #333;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 8px;
  border-radius: 2px;
}

.bind-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.status-info {
  display: flex;
  align-items: center;
}

.status-info .label {
  font-weight: 500;
  margin-right: 10px;
}

.captcha-row {
  display: flex;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 22px;
}

.avatar-info {
  margin-left: 24px;
}

.avatar-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 500;
}

.avatar-tip {
  color: #909399;
  font-size: 13px;
  margin: 0 0 12px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.switch-label {
  margin-left: 12px;
  font-size: 13px;
  color: #606266;
}

@media (max-width: 768px) {
  .settings-content {
    flex-direction: column;
  }
  
  .settings-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .settings-form {
    max-width: 100%;
  }
  
  .bind-status {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style> 